package cn.yyh.pet.service.impl;

import cn.yyh.basic.service.impl.BaseServiceImpl;
import cn.yyh.basic.utils.PageInfo;
import cn.yyh.org.domain.Employee;
import cn.yyh.org.mapper.EmployeeMapper;
import cn.yyh.pet.domain.Pet;
import cn.yyh.pet.domain.PetDetail;
import cn.yyh.pet.mapper.PetDetailMapper;
import cn.yyh.pet.mapper.PetMapper;
import cn.yyh.pet.query.PetQuery;
import cn.yyh.pet.service.IPetService;
import cn.yyh.user.mapper.UserMapper;
import cn.yyh.user.pojo.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨永航
 * @version 1.0
 * @Title: PetServiceImpl
 * @Package: cn.yyh.pet.service.impl
 * @date 2021/7/6
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<PetMapper, Pet> implements IPetService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PetDetailMapper detailMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void save(Pet pet) {
        super.save(pet);
        PetDetail detail = pet.getDetail();
        if (detail != null) {
            detail.setPet_id(pet.getId());
            detailMapper.save(detail);
        }
    }

    @Override
    public PageInfo<Pet> pageQuery(PetQuery query, Long id) {

        Employee employee = employeeMapper.getByLoginInfoId(id);
        if (employee != null) {
            if (!ObjectUtils.isEmpty(employee.getShopId())) {
                query.setShop_id(employee.getShopId());
            }
        }
        Integer count = baseMapper.countByQuery(query);
        List<Pet> pets = baseMapper.pageQuery(query);
        PageInfo<Pet> info = new PageInfo<>();
        info.setRows(pets);
        info.setTotals(count);
        return info;
    }

    @Override
    public void onSale(List<Long> ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("onsaleTime", new Date());
        baseMapper.onSale(map);
    }

    @Override
    public void offSale(List<Long> ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("offsaleTime", new Date());
        baseMapper.offSale(map);
    }

    @Override
    public Pet loadById(Long id) {
        return baseMapper.loadById(id);
    }

    @Override
    public Pet getPetDetailsById(Long id) {

        return baseMapper.loadByIdDetail(id);
    }

    @Override
    public void adopt(Long id, Long id1) {

        User user = userMapper.getByLoginInfoId(id1);
        Pet pet = baseMapper.getById(id);
        // 给宠物设置userId
        pet.setUser_id(user.getId());
        // 把宠物下架
        pet.setState(0);
        pet.setOffsaletime(new Date());
        baseMapper.update(pet);

    }

}
